#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
图片下载和解密工具 - 简化版
"""

import json
import os
import requests
from pathlib import Path


# 解密参数
AR = 100  # 解密的字节数
DECRYPT_KEY = "2020-zq3-888"  # 解密密钥


def decrypt_image_data(encrypted_data: bytes) -> bytes:
    """解密图片数据"""
    data = bytearray(encrypted_data)
    
    # 对前 AR 个字节进行 XOR 解密
    for i in range(min(AR, len(data))):
        data[i] ^= ord(DECRYPT_KEY[i % len(DECRYPT_KEY)])
    
    return bytes(data)


def download_and_decrypt_image(image_url: str, output_path: str) -> bool:
    """下载并解密单张图片"""
    try:
        print(f'正在下载: {image_url}')
        
        # 下载图片
        response = requests.get(image_url, timeout=30, headers={
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
        })
        
        if response.status_code != 200:
            print(f'✗ HTTP错误 {response.status_code}: {image_url}')
            return False
        
        # 解密图片数据
        encrypted_data = response.content
        decrypted_data = decrypt_image_data(encrypted_data)
        
        # 确保输出目录存在
        output_dir = Path(output_path).parent
        output_dir.mkdir(parents=True, exist_ok=True)
        
        # 保存解密后的图片
        with open(output_path, 'wb') as f:
            f.write(decrypted_data)
        
        print(f'✓ 保存成功: {output_path}')
        return True
        
    except Exception as error:
        print(f'✗ 下载失败 {image_url}: {error}')
        return False


def extract_image_urls(decrypted_data: dict) -> list:
    """从解密数据中提取图片URL列表"""
    image_urls = []
    domain = decrypted_data.get('data', {}).get('domain')
    
    if not domain:
        print("未找到 domain 字段")
        return image_urls
    
    print(f'域名: {domain}')
    
    # 检查是否有 imgList（漫画章节图片列表）
    if 'imgList' in decrypted_data.get('data', {}) and isinstance(decrypted_data['data']['imgList'], list):
        print(f'找到 imgList，包含 {len(decrypted_data["data"]["imgList"])} 张图片')
        
        chapter_id = decrypted_data['data'].get('chapterId', 'unknown')
        chapter_title = decrypted_data['data'].get('chapterTitle', 'chapter')
        
        for index, img_path in enumerate(decrypted_data['data']['imgList']):
            filename = f"{chapter_id}_{chapter_title}_{str(index + 1).zfill(3)}_{Path(img_path).name}"
            
            image_urls.append({
                'url': domain + img_path,
                'filename': filename,
                'type': 'chapter',
                'chapterId': chapter_id,
                'chapterTitle': chapter_title,
                'pageIndex': index + 1,
            })
        
        # 添加封面图片
        if decrypted_data['data'].get('coverImg'):
            image_urls.insert(0, {
                'url': domain + decrypted_data['data']['coverImg'],
                'filename': f"{chapter_id}_{chapter_title}_000_cover_{Path(decrypted_data['data']['coverImg']).name}",
                'type': 'cover',
                'chapterId': chapter_id,
                'chapterTitle': chapter_title,
            })
    
    # 检查是否有 data 数组（漫画列表数据）
    elif 'data' in decrypted_data.get('data', {}) and isinstance(decrypted_data['data']['data'], list):
        print(f'找到漫画列表数据，包含 {len(decrypted_data["data"]["data"])} 个漫画')
        
        for index, item in enumerate(decrypted_data['data']['data']):
            # 提取封面图片
            if item.get('coverImg'):
                image_urls.append({
                    'url': domain + item['coverImg'],
                    'filename': f"cover_{item.get('comicsId', index)}_{Path(item['coverImg']).name}",
                    'type': 'cover',
                    'comicsId': item.get('comicsId'),
                    'title': item.get('comicsTitle'),
                })
            
            # 提取背景图片
            if item.get('backImg') and item['backImg'] != item.get('coverImg'):
                image_urls.append({
                    'url': domain + item['backImg'],
                    'filename': f"back_{item.get('comicsId', index)}_{Path(item['backImg']).name}",
                    'type': 'back',
                    'comicsId': item.get('comicsId'),
                    'title': item.get('comicsTitle'),
                })
    
    return image_urls


def batch_download_images(image_list: list, output_dir: str = "./images", max_images: int = 0):
    """批量下载图片"""
    if max_images > 0:
        image_list = image_list[:max_images]
        print(f'限制下载数量为 {max_images} 张')
    
    print(f'\n开始批量下载 {len(image_list)} 张图片...')
    print(f'输出目录: {output_dir}\n')
    
    success_count = 0
    fail_count = 0
    
    for i, image_info in enumerate(image_list):
        output_path = Path(output_dir) / image_info['filename']
        success = download_and_decrypt_image(image_info['url'], str(output_path))
        
        if success:
            success_count += 1
        else:
            fail_count += 1
        
        # 显示进度
        print(f'进度: {i + 1}/{len(image_list)} (成功: {success_count}, 失败: {fail_count})')
        
        # 避免请求过于频繁
        if i < len(image_list) - 1:
            import time
            time.sleep(1)
    
    print(f'\n=== 下载完成 ===')
    print(f'总计: {len(image_list)}')
    print(f'成功: {success_count}')
    print(f'失败: {fail_count}')


def main():
    """主函数"""
    import argparse
    
    parser = argparse.ArgumentParser(description='下载并解密图片')
    parser.add_argument('-d', '--data', default='./decrypted_data.json', help='指定解密数据文件 (默认: ./decrypted_data.json)')
    parser.add_argument('-o', '--output', default='./images', help='指定输出目录 (默认: ./images)')
    parser.add_argument('-m', '--max', type=int, default=0, help='最大下载数量 (默认: 不限制)')
    
    args = parser.parse_args()
    
    try:
        # 读取解密数据
        print(f'读取解密数据: {args.data}')
        with open(args.data, 'r', encoding='utf-8') as f:
            decrypted_data = json.load(f)
        
        # 提取图片URL
        image_urls = extract_image_urls(decrypted_data)
        
        if not image_urls:
            print("没有找到图片URL")
            return
        
        print(f'找到 {len(image_urls)} 张图片')
        
        # 批量下载
        batch_download_images(image_urls, args.output, args.max)
        
    except Exception as error:
        print(f"处理失败: {error}")


if __name__ == '__main__':
    main()
